package com.milo.coding.concurrent.tools;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Author milo
 * @Date 2021-02-01 13:19:13
 * @Description 限流，降级。。。可用于流量控制，限制最大的并发访问数
 */
public class SemaphoreRunner {

    public static void main(String[] args) {
        // 这里的入参 是设置AQS的state，控制一次通过的数量
        Semaphore semaphore = new Semaphore(2);
        for (int i=0;i<10;i++){
            new Thread(new Task(semaphore,"milo+"+i)).start();
        }
    }

    static class Task extends Thread{
        Semaphore semaphore;

        public Task(Semaphore semaphore,String tname){
            super(tname);
            this.semaphore = semaphore;
            //this.setName(tname);
        }

        public void run() {
            try {
                // semaphore.acquireUninterruptibly(); //非中断方式获取

                semaphore.acquire(); // 获取公共资源，这里也可以传入每次获取的票据数量   // 中断方式获取

                System.out.println(Thread.currentThread().getName()+":aquire() at time:"+System.currentTimeMillis());
                Thread.sleep(5000);

                semaphore.release();

                // if(semaphore.tryAcquire(500,TimeUnit.MILLISECONDS)){
                //     System.out.println(Thread.currentThread().getName()+":aquire() at time:"+System.currentTimeMillis());
                //     Thread.sleep(5000);
                //     semaphore.release();//释放公共资源
                // }else{
                //     fallback();
                // }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public void fallback(){
            System.out.println("降级");
        }
    }
}
